package com.jianyun.jyzs.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import org.apache.commons.lang3.StringUtils;

import com.google.gson.Gson;
import com.hannesdorfmann.mosby3.mvp.MvpActivity;
import com.jianyun.jyzs.R;
import com.jianyun.jyzs.bean.FlowHtmlJsonBean;
import com.jianyun.jyzs.bean.LeaveMenuBean;
import com.jianyun.jyzs.bean.User;
import com.jianyun.jyzs.presenter.FlowExaminePresenter;
import com.jianyun.jyzs.utils.Const;
import com.jianyun.jyzs.utils.DataFactory;
import com.jianyun.jyzs.utils.LoginCache;
import com.jianyun.jyzs.utils.RceLog;
import com.jianyun.jyzs.utils.SearchPopHtmlWindow;
import com.jianyun.jyzs.utils.UtilsStyle;
import com.jianyun.jyzs.utils.WorkFlowActHelper;
import com.jianyun.jyzs.view.iview.IFlowExamineView;

import java.util.ArrayList;
import java.util.Stack;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author 杨仕俊
 * @description 流程审批html
 * Created by yangshijun on 2018/11/8.
 */

public class FlowExamineHtmlActivity extends MvpActivity<IFlowExamineView,
        FlowExaminePresenter> implements IFlowExamineView {

    @BindView(R.id.imgbtn_custom_nav_back)
    ImageButton imgbtnCustomNavBack;
    @BindView(R.id.imgbtn_custom_nav_finish)
    ImageButton imgbtnCustomNavFinish;
    @BindView(R.id.tv_custom_nav_title)
    TextView tvCustomNavTitle;
    @BindView(R.id.tv_custom_nav_sub_title)
    TextView tvCustomNavSubTitle;
    @BindView(R.id.ll_custom_nav_title)
    LinearLayout llCustomNavTitle;
    @BindView(R.id.tv_custom_nav_option)
    TextView tvCustomNavOption;
    @BindView(R.id.imgbtn_custom_nav_option)
    ImageButton imgbtnCustomNavOption;
    @BindView(R.id.rl_actionbar)
    RelativeLayout rlActionbar;
    @BindView(R.id.webView)
    WebView webView;
    @BindView(R.id.progressBar)
    ProgressBar progressBar;
    @BindView(R.id.imgbtn_custom_nav)
    ImageButton imgbtnCustomNav;

    private String mPrevUrl = "";
    private String initUrl = "";
    private String StartUrl = "";
    private boolean askedgalleryPermission = false;
    private int galleryPermissionReqCode = 202;
    public String[] data;//用来保存搜索的条件
    private String userId;
    private WebSettings webSettings;
    public SearchPopHtmlWindow searchPopWindow;
    public TextView textViewTemp;//popwindow上
    public String createUserId;
    private int flowSwtich;
    private String isSercah;
    private int page = 1;
    public static int shenpiRefresh = 100;
    public static int shenPiRefreshYes = 102;

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            try {
                Log.i("test", "搜索后2：" + mPrevUrl);
                String type = (String) msg.obj;
                int i = initUrl.indexOf("type=");
                String substring = initUrl.substring(0, i);
                Log.i("test", "截取：" + i + "\n" + substring);
                //String replaceURL = replaceAccessToken(initUrl, "type", type);
                //Log.i("test", "替换取：" + replaceURL);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    };
    private OAWebViewClient oaWebViewClient;
    private ArrayList<LeaveMenuBean> leaveMenuBeans;
    private ArrayList<LeaveMenuBean.HtmlJsInitBean> htmlJsInitBean;
    private FlowHtmlJsonBean flowHtmlJsonBean;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        UtilsStyle.setStatusBarMode(this, true);
        setContentView(R.layout.rce_activity_webview);
        ButterKnife.bind(this);
        initData();
        initView();

    }


    private void initData() {
        String url = getIntent().getStringExtra("url");
        if (!TextUtils.isEmpty(url)) {
            if (url.startsWith("http") || url.startsWith("https")) {
                mPrevUrl = url;
            } else {
                mPrevUrl = LoginCache.getInstance().getLoginCache().getErpRootUrl() + url;
            }
        }
        //initUrl = mPrevUrl;
        flowSwtich = LoginCache.getInstance().getFlowSwtich();
        isSercah = getIntent().getStringExtra("isSercah");

    }


    private void initView() {

        data = new String[4];
        userId = LoginCache.getInstance().getUserInfo().getUserId();
        webSettings = webView.getSettings();
        //设置WebView属性，能够执行Javascript脚本
        webSettings.setJavaScriptEnabled(true);
        //设置可以访问文件
        webSettings.setAllowFileAccess(true);
        //设置支持缩放
        webSettings.setBuiltInZoomControls(false);
        //放开storage缓存机制
        webSettings.setDomStorageEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        oaWebViewClient = new OAWebViewClient();
        webView.setWebViewClient(oaWebViewClient);
        webView.setWebChromeClient(new OAWebChromeClient());
        webView.setDownloadListener(new MyWebViewDownLoadListener());
        webView.addJavascriptInterface(new JavaScriptObject(), "control");//传递对象进行交互
        Log.i("test", "html中：" + mPrevUrl);
        StartUrl = mPrevUrl;
        if ("1".equals(isSercah)) {
            imgbtnCustomNavOption.setVisibility(View.VISIBLE);
            imgbtnCustomNav.setVisibility(View.INVISIBLE);
        } else if ("2".equals(isSercah)) {
            imgbtnCustomNav.setVisibility(View.VISIBLE);
        } else {
            imgbtnCustomNavOption.setVisibility(View.INVISIBLE);
        }

        imgbtnCustomNavOption.setImageResource(R.drawable.detail_search_default);
        searchData();
    }

    /**
     * 点击查询条件搜索后执行此方法
     */
    public void searchData() {
        if (data != null) {
            mPrevUrl += "&insName=" + (data[0] == null ? "" : data[0]);
            mPrevUrl += "&taskName=" + (data[1] == null ? "" : data[1]);
            mPrevUrl += "&sendEmployeeid=" + (data[2] == null ? "" : createUserId);
            mPrevUrl += "&sendTime=" + (data[3] == null ? "" : data[3]);
        }
        webView.loadUrl(mPrevUrl);
        Log.i("test", "审批URL:" + mPrevUrl);
        mPrevUrl = initUrl;


    }

    public void pageGoBack(WebView web, OAWebViewClient client) {
        String url = client.onPageUrl();
        if (url.equals(StartUrl)) {
            finish();
        } else {
            imgbtnCustomNavOption.setVisibility(View.INVISIBLE);
            webView.loadUrl(StartUrl);
        }
    }

    public class JavaScriptObject {


        @JavascriptInterface
        public void setTypes(String type) {
            Message message = new Message();
            message.what = 1;
            message.obj = type;
            mHandler.sendMessage(message);
        }

        @JavascriptInterface
        public void setSerachClick(boolean isClick) {
            page = 1;
            Log.i("test", "点击搜索：" + isClick);
        }

        @JavascriptInterface
        public void hidePage() {
            Log.i("test", "审批刷新");
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == WorkFlowActHelper.GETUSER && resultCode == RESULT_OK) {
            ArrayList<User> users = (ArrayList<User>) data.getSerializableExtra(Const.SELECTED_CONTACTS);
            RceLog.d("lml", "list.toString()=" + users.toString());
            if (textViewTemp != null) {
                try {
                    User user = users.get(1);
                    createUserId = user.getServerUserId();
                    textViewTemp.setText(user.getName());
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

        }

        if (requestCode == shenpiRefresh && resultCode == shenPiRefreshYes) {
            //需要刷新界面
            Log.i("test", "刷新列表界面");
            webView.loadUrl(mPrevUrl);
        }
    }

    @OnClick({R.id.imgbtn_custom_nav_back, R.id.imgbtn_custom_nav_finish, R.id.imgbtn_custom_nav_option
            , R.id.imgbtn_custom_nav})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.imgbtn_custom_nav_back:
                if (webView.canGoBack()) {
                    pageGoBack(webView, oaWebViewClient);
                    //webView.goBack();
                    page = 1;
//                    if (webView.canGoBack()) {
//                        imgbtnCustomNavOption.setVisibility(View.VISIBLE);
//                    } else {
//                        imgbtnCustomNavOption.setVisibility(View.INVISIBLE);
//                    }

                } else {
                    finish();
                }
                break;
            case R.id.imgbtn_custom_nav_finish:
                finish();
                break;
            case R.id.imgbtn_custom_nav_option:
                //右上角
//                searchPopWindow = new SearchPopHtmlWindow(this, R.layout.popupwindow_workflow_search, data);
//                searchPopWindow.showPopupWindow(imgbtnCustomNavOption);
                if (flowHtmlJsonBean != null) {
                    String fnName = flowHtmlJsonBean.getMenuJson().get(0).getFnName();
                    webView.loadUrl("javascript:" + fnName);
                }

                break;
            case R.id.imgbtn_custom_nav:
                Intent intent = new Intent(this, FlowSwtichActivity.class);
                startActivity(intent);
                break;

        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    class MyWebViewDownLoadListener implements DownloadListener {

        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
            showFile(url);
        }

    }

    public void showFile(String url) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            //有权限
            //其他手机 下载 打开
            startActivity((new Intent(this, ShowFileActivity.class))
                    .putExtra("type", -1)
                    .putExtra("id", -1)
                    .putExtra("folderID", "workFlow")
                    .putExtra("remotepath", url));
        } else if (!askedgalleryPermission) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    galleryPermissionReqCode);
            askedgalleryPermission = true;
        }
    }

    //Web视图
    private class OAWebViewClient extends WebViewClient {

        public String onPageUrl = "";

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {//网页页面开始加载的时候
            super.onPageStarted(view, url, favicon);
            Log.i("test", "网页：" + url);
            onPageUrl = url;


        }


        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
//	         //页面下载完毕,却不代表页面渲染完毕显示出来
//            if (webview.getContentHeight() != 0) { //这个时候网页才显示
            progressBar.setVisibility(View.INVISIBLE);

            // 换成下面该方法即可
            webView.evaluateJavascript("javascript:getPhoneMenu()", new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {
                    Log.i("test", "菜单的：" + value);
                    //字符串替换
                    //此处为 js 返回的结果
                    if ("null".equals(value)) {

                    } else {
                        //page=3;
                        Gson gson = new Gson();
                        flowHtmlJsonBean = gson.fromJson(value, FlowHtmlJsonBean.class);
                        //Log.i("test", "解析：" + flowHtmlJsonBean.toString());

                    }
                }
            });

        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.i("test", "加载：" + url);
            // handle different requests for different type of files
            // this example handles downloads requests for .apk and .mp3 files
            // everything else the webview can handle normally
//            if (url.endsWith("isDowload=yes")) {
            //跳转界面
            if (1 == page) {
                imgbtnCustomNavOption.setVisibility(View.VISIBLE);
                view.loadUrl(url);
                page = 3;
                initUrl = url;
                mPrevUrl = url;
                Log.i("test", "加载2：" + initUrl);
            } else {
                page = 3;
                Intent intent = new Intent(FlowExamineHtmlActivity.this, FlowExamineDetailActivity.class);
                intent.putExtra("url", url);
                //startActivity(intent);
                startActivityForResult(intent, shenpiRefresh);
            }

            return true;
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            //这里进行无网络或错误处理，具体可以根据errorCode的值进行判断，做跟详细的处理。
            view.loadUrl("file:///android_asset/error.html");
        }

        public String onPageUrl() {
            return onPageUrl;
        }
    }

    private class OAWebChromeClient extends WebChromeClient {

        @Override
        public void onReceivedTitle(WebView view, String title) {
            if (tvCustomNavTitle != null && !TextUtils.isEmpty(title)) {
                tvCustomNavTitle.setText(title);
            }
        }

    }


    @NonNull
    @Override
    public FlowExaminePresenter createPresenter() {
        return new FlowExaminePresenter();
    }
}
